<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>GM工具 - 玩家管理</title>
    <link rel="stylesheet" href="css/style.css">
    <style>
        /* 玩家管理页面特定样式 */
        body {
            display: block;
            height: auto;
            min-height: 100vh;
            background-color: #f0f2f5;
            background-image: none;
        }
        
        .main-container {
            display: flex;
            flex-direction: column;
            min-height: 100vh;
        }
        
        .header {
            background-color: #2c3e50;
            color: white;
            padding: 15px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .header h1 {
            margin: 0;
            font-size: 24px;
        }
        
        .user-info {
            font-size: 14px;
            display: flex;
            align-items: center;
        }
        
        .back-button {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 6px 12px;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 10px;
            transition: background-color 0.3s ease;
        }
        
        .back-button:hover {
            background-color: #2980b9;
        }
        
        .logout-button {
            background-color: #e74c3c;
            color: white;
            border: none;
            padding: 6px 12px;
            border-radius: 4px;
            cursor: pointer;
            margin-left: 10px;
            transition: background-color 0.3s ease;
        }
        
        .logout-button:hover {
            background-color: #c0392b;
        }
        
        .content {
            padding: 30px 20px;
            max-width: 1200px;
            margin: 0 auto;
            flex: 1;
            width: 100%;
        }
        
        .page-title {
            margin-bottom: 25px;
            color: #2c3e50;
            text-align: center;
        }
        
        .section {
            background-color: white;
            border-radius: 8px;
            padding: 25px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            margin-bottom: 30px;
        }
        
        .section-title {
            margin-top: 0;
            margin-bottom: 20px;
            color: #2c3e50;
            border-bottom: 1px solid #eee;
            padding-bottom: 12px;
        }
        
        /* 玩家列表样式 */
        .players-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        
        .players-table th,
        .players-table td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #eee;
        }
        
        .players-table th:first-child,
        .players-table td:first-child {
            width: 40px;
            text-align: center;
        }
        
        .players-table th {
            background-color: #f8f9fa;
            font-weight: 600;
            color: #495057;
        }
        
        .players-table tr:hover {
            background-color: #f8f9fa;
        }
        
        .players-table tr.selected {
            background-color: #e3f2fd;
        }
        
        /* 玩家标签样式 */
        .selected-players-list {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            margin-top: 10px;
        }
        
        .player-tag {
            background-color: #e3f2fd;
            border: 1px solid #90caf9;
            border-radius: 16px;
            padding: 4px 12px;
            display: inline-flex;
            align-items: center;
            font-size: 14px;
        }
        
        .remove-player-btn {
            background: none;
            border: none;
            color: #6c757d;
            margin-left: 8px;
            cursor: pointer;
            font-size: 16px;
            line-height: 1;
            padding: 0;
            width: 20px;
            height: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .remove-player-btn:hover {
            color: #dc3545;
        }
        
        /* 搜索区域样式 */
        .search-container {
            display: flex;
            margin-bottom: 20px;
            gap: 10px;
        }
        
        .search-input {
            flex: 1;
            padding: 10px 15px;
            border: 2px solid #e0e0e0;
            border-radius: 6px;
            font-size: 16px;
        }
        
        .search-input:focus {
            outline: none;
            border-color: #3498db;
        }
        
        .search-button {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s ease;
        }
        
        .search-button:hover {
            background-color: #2980b9;
        }
        
        /* 选中玩家信息样式 */
        .selected-player {
            background-color: #e3f2fd;
            border-left: 4px solid #3498db;
            padding: 15px;
            border-radius: 4px;
            margin-bottom: 20px;
        }
        
        .selected-player-label {
            font-weight: bold;
            margin-right: 10px;
        }
        
        /* GM选项样式 */
        .gm-options {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
        }
        
        .option-card {
            background-color: #f8f9fa;
            border-radius: 6px;
            padding: 20px;
            border: 1px solid #e9ecef;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: 500;
            color: #495057;
        }
        
        .form-control {
            width: 100%;
            padding: 10px 15px;
            border: 1px solid #ced4da;
            border-radius: 4px;
            font-size: 16px;
        }
        
        .form-control:focus {
            outline: none;
            border-color: #3498db;
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
        }
        
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            font-weight: 500;
            transition: all 0.3s ease;
        }
        
        .btn-primary {
            background-color: #3498db;
            color: white;
        }
        
        .btn-primary:hover {
            background-color: #2980b9;
        }
        
        .btn-success {
            background-color: #27ae60;
            color: white;
        }
        
        .btn-success:hover {
            background-color: #229954;
        }
        
        .loading {
            text-align: center;
            padding: 20px;
            color: #6c757d;
        }
        
        .spinner {
            border: 3px solid #f3f3f3;
            border-top: 3px solid #3498db;
            border-radius: 50%;
            width: 24px;
            height: 24px;
            animation: spin 1s linear infinite;
            margin: 0 auto 10px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .no-data {
            text-align: center;
            padding: 40px 20px;
            color: #6c757d;
        }
        
        /* 物品列表样式 */
        .items-list-container {
            background-color: #f8f9fa;
            border-radius: 4px;
            padding: 15px;
            min-height: 150px;
        }
        
        .items-list {
            margin-bottom: 15px;
        }
        
        .item-list-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px;
            background-color: white;
            border: 1px solid #e9ecef;
            border-radius: 4px;
            margin-bottom: 8px;
        }
        
        .item-info {
            font-size: 14px;
            color: #495057;
        }
        
        .btn-remove {
            padding: 5px 10px;
            background-color: #dc3545;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
        }
        
        .btn-remove:hover {
            background-color: #c82333;
        }
        
        .empty-list {
            text-align: center;
            padding: 30px;
            color: #6c757d;
            font-style: italic;
        }
        
        /* 选项卡样式 */
        .tabs {
            display: flex;
            margin-bottom: 25px;
            border-bottom: 2px solid #e9ecef;
        }
        
        .tab-button {
            padding: 12px 24px;
            background: none;
            border: none;
            cursor: pointer;
            font-size: 16px;
            font-weight: 500;
            color: #6c757d;
            border-bottom: 3px solid transparent;
            transition: all 0.3s ease;
        }
        
        .tab-button:hover {
            color: #3498db;
        }
        
        .tab-button.active {
            color: #3498db;
            border-bottom-color: #3498db;
        }
        
        .tab-content {
            display: none;
        }
        
        .tab-content.active {
            display: block;
        }
        
        /* 直播间列表样式 */
        .rooms-list {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 15px;
            margin-top: 15px;
        }
        
        .room-card {
            background-color: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 6px;
            padding: 15px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .room-card:hover {
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            border-color: #3498db;
        }
        
        .room-info {
            margin-bottom: 10px;
        }
        
        .room-info label {
            font-weight: 500;
            color: #495057;
            margin-right: 8px;
        }
        
        .room-info span {
            color: #6c757d;
        }
        
        .players-list {
            margin-top: 10px;
            padding-top: 10px;
            border-top: 1px solid #dee2e6;
        }
        
        .player-item {
            display: flex;
            justify-content: space-between;
            padding: 5px 0;
            font-size: 14px;
        }
        
        /* 响应式设计 */
        @media (max-width: 768px) {
            .content {
                padding: 20px 15px;
            }
            
            .section {
                padding: 20px 15px;
            }
            
            .search-container {
                flex-direction: column;
            }
            
            .players-table {
                font-size: 14px;
            }
            
            .players-table th,
            .players-table td {
                padding: 8px 10px;
            }
        }
    </style>
</head>
<body>
    <div class="main-container">
        <div class="header">
            <h1>GM工具 - 玩家与直播间管理</h1>
            <div class="user-info">
                <button class="back-button" onclick="goBack()">返回主页</button>
                <span id="welcomeMessage">欢迎，管理员</span>
                <button class="logout-button" onclick="logout()">退出登录</button>
            </div>
        </div>
    
        <div class="content">
            <h2 class="page-title">玩家与直播间管理</h2>
            
            <!-- 玩家管理标题 -->
            <h3 class="section-title">玩家列表管理</h3>
            
            <!-- 玩家管理内容区域 -->
            <div id="players-tab" class="tab-content active">
            <div class="section">
                <h3 class="section-title">玩家列表</h3>
                
                <!-- 搜索功能 -->
                <div class="search-container">
                    <input type="text" id="searchInput" class="search-input" placeholder="输入玩家名称进行搜索...">
                    <button class="search-button" onclick="searchPlayers()">搜索</button>
                </div>
                
                <!-- 玩家表格 -->
                <div id="playersTableContainer">
                    <table class="players-table">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>玩家名称</th>
                                <th>所在房间</th>
                                <th>最近游玩时间</th>
                            </tr>
                        </thead>
                        <tbody id="playersTableBody">
                            <!-- 玩家数据将通过JavaScript动态填充 -->
                        </tbody>
                    </table>
                </div>
            </div>
            
            <!-- 选中玩家信息 -->
            <div class="section">
                <h3 class="section-title">选中玩家</h3>
                <div id="selectedPlayerInfo" class="selected-player" style="display: none;">
                    <span class="selected-player-label">选中的玩家:</span>
                </div>
                <div id="noPlayerSelected" style="text-align: center; color: #6c757d;">
                    请从上方列表中选择玩家
                </div>
            </div>
            
            <!-- GM选项 -->
            <div class="section">
                <h3 class="section-title">GM选项</h3>
                <div class="gm-options">
                    <div class="option-card">
                        <h4>添加物品</h4>
                        <div class="form-group">
                            <label for="itemCategory">物品分类</label>
                            <select id="itemCategory" class="form-control">
                                <option value="">请选择物品分类</option>
                                <!-- 物品分类将通过JavaScript动态填充 -->
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="itemId">物品ID</label>
                            <input type="number" id="itemId" class="form-control" placeholder="请输入物品ID">
                        </div>
                        <div class="form-group">
                            <label for="itemCount">数量</label>
                            <input type="number" id="itemCount" class="form-control" value="1" min="1">
                        </div>
                        <button class="btn btn-primary" onclick="addItemToList()">添加到列表</button>
                    </div>
                    
                    <div class="option-card">
                        <h4>物品列表</h4>
                        <div id="itemsListContainer" class="items-list-container">
                            <div id="itemsList" class="items-list">
                                <!-- 物品列表将通过JavaScript动态填充 -->
                            </div>
                            <button id="sendItemsBtn" class="btn btn-success" onclick="sendItemsFromList()" disabled>获取道具</button>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 玩家管理内容区域结束 -->
        </div>
    </div>

    <script src="js/utils.js"></script>
    <script>
        // 当前选中的玩家数组
        let selectedPlayers = [];
        // 物品分类数据
        let itemCategories = {};
        // 待发送的物品列表
        let itemsToSend = {};
        
        // 页面加载时初始化
        window.onload = function() {
            // 检查登录状态
            checkLoginStatus();
            
            // 显示欢迎信息
            showWelcomeMessage();
            
            // 注意：这里不再默认切换到players标签，而是通过DOMContentLoaded事件切换到直播间标签
            // 加载所有玩家信息 - 仍然加载，以备用户切换到玩家标签时使用
            loadAllPlayers();
            
            // 加载物品分类
            loadItemCategories();
            
            // 绑定回车键搜索事件
            document.getElementById('searchInput').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    searchPlayers();
                }
            });
        };
        
        // 检查登录状态
        function checkLoginStatus() {
            if (!sessionStorage.getItem('gmToken')) {
                window.location.href = '/gm/login.html';
                return false;
            }
            return true;
        }
        
        // 显示欢迎信息
        function showWelcomeMessage() {
            const username = sessionStorage.getItem('gmUsername');
            if (username) {
                document.getElementById('welcomeMessage').textContent = `欢迎，${username}`;
            }
        }
        
        // 返回主页
        function goBack() {
            window.location.href = '/gm/index.html';
        }
        
        // 退出登录
        function logout() {
            if (confirm('确定要退出登录吗？')) {
                // 清除会话信息
                sessionStorage.removeItem('gmToken');
                sessionStorage.removeItem('gmUsername');
                showMessage('已成功退出登录', 'info');
                // 跳转到登录页面
                setTimeout(() => {
                    window.location.href = '/gm/login.html';
                }, 1000);
            }
        }
        
        // 加载所有玩家信息
        async function loadAllPlayers() {
            try {
                const token = sessionStorage.getItem('gmToken');
                if (!token) {
                    showMessage('未找到认证令牌，请重新登录', 'error');
                    return;
                }
                
                // 显示加载状态
                const tableBody = document.getElementById('playersTableBody');
                tableBody.innerHTML = '<tr><td colspan="4"><div class="loading"><div class="spinner"></div>正在加载玩家数据...</div></td></tr>';
                
                // 发送请求获取所有玩家信息
                const response = await fetch('/gm/userInfo', {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                        'token': token
                    }
                });
                
                const result = await response.json();
                
                if (result.code === 200 && result.data) {
                    displayPlayers(result.data);
                } else {
                    tableBody.innerHTML = '<tr><td colspan="4"><div class="no-data">暂无玩家数据</div></td></tr>';
                    showMessage(result.message || '获取玩家数据失败', 'error');
                }
            } catch (error) {
                console.error('加载玩家数据出错:', error);
                document.getElementById('playersTableBody').innerHTML = '<tr><td colspan="4"><div class="no-data">加载数据时发生错误</div></td></tr>';
                showMessage('加载玩家数据时发生错误', 'error');
            }
        }
        
        // 显示玩家列表
        function displayPlayers(players) {
            const tableBody = document.getElementById('playersTableBody');
            
            if (!players || players.length === 0) {
                tableBody.innerHTML = '<tr><td colspan="4"><div class="no-data">暂无玩家数据</div></td></tr>';
                return;
            }
            
            let html = '';
            players.forEach(player => {
                html += `
                    <tr>
                        <td><input type="checkbox" class="player-checkbox" value="${player.id}" data-name="${player.name}" onchange="togglePlayerSelection(${player.id}, '${player.name}', this.checked)"></td>
                        <td>${player.id}</td>
                        <td>${player.name}</td>
                        <td>${player.playingRoomName || '无'}</td>
                        <td>${formatTimestamp(player.recentPlaytime)}</td>
                    </tr>
                `;
            });
            
            tableBody.innerHTML = html;
        }
        
        // 格式化时间戳
        function formatTimestamp(timestamp) {
            if (!timestamp) return '未知';
            
            // 假设时间戳是以秒为单位
            const date = new Date(timestamp * 1000);
            return date.toLocaleString('zh-CN');
        }
        
        // 搜索玩家
        async function searchPlayers() {
            const searchName = document.getElementById('searchInput').value.trim();
            
            if (!searchName) {
                // 如果搜索框为空，则加载所有玩家
                loadAllPlayers();
                return;
            }
            
            try {
                const token = sessionStorage.getItem('gmToken');
                if (!token) {
                    showMessage('未找到认证令牌，请重新登录', 'error');
                    return;
                }
                
                // 显示加载状态
                const tableBody = document.getElementById('playersTableBody');
                tableBody.innerHTML = '<tr><td colspan="4"><div class="loading"><div class="spinner"></div>正在搜索玩家...</div></td></tr>';
                
                // 发送请求搜索玩家
                const response = await fetch(`/gm/findUser?name=${encodeURIComponent(searchName)}`, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        'token': token
                    }
                });
                
                const result = await response.json();
                
                if (result.code === 200 && result.data) {
                    displayPlayers(result.data);
                } else {
                    tableBody.innerHTML = '<tr><td colspan="4"><div class="no-data">未找到匹配的玩家</div></td></tr>';
                    showMessage(result.message || '搜索玩家失败', 'error');
                }
            } catch (error) {
                console.error('搜索玩家出错:', error);
                document.getElementById('playersTableBody').innerHTML = '<tr><td colspan="4"><div class="no-data">搜索时发生错误</div></td></tr>';
                showMessage('搜索玩家时发生错误', 'error');
            }
        }
        
        // 切换玩家选择状态
        function togglePlayerSelection(playerId, playerName, isChecked) {
            // 找到当前行并更新高亮状态
            const row = event.target.closest('tr');
            if (isChecked) {
                // 添加到选中列表
                if (!selectedPlayers.some(p => p.id === playerId)) {
                    selectedPlayers.push({ id: playerId, name: playerName });
                }
                row.classList.add('selected');
            } else {
                // 从选中列表中移除
                selectedPlayers = selectedPlayers.filter(p => p.id !== playerId);
                row.classList.remove('selected');
            }
            
            // 更新选中玩家显示
            updateSelectedPlayersDisplay();
            
            // 更新发送按钮状态
            updateSendButtonState();
        }
        
        // 更新选中玩家显示
        function updateSelectedPlayersDisplay() {
            const selectedPlayerInfo = document.getElementById('selectedPlayerInfo');
            const noPlayerSelected = document.getElementById('noPlayerSelected');
            
            if (selectedPlayers.length > 0) {
                // 显示选中的玩家列表
                let playersHtml = '<div class="selected-players-list">';
                selectedPlayers.forEach((player, index) => {
                    playersHtml += `
                        <div class="player-tag">
                            ${player.name} (ID: ${player.id})
                            <button class="remove-player-btn" onclick="removePlayerFromSelection(${player.id})">&times;</button>
                        </div>
                    `;
                });
                playersHtml += '</div>';
                
                selectedPlayerInfo.innerHTML = `
                    <span class="selected-player-label">选中的玩家 (${selectedPlayers.length}):</span>
                    ${playersHtml}
                `;
                selectedPlayerInfo.style.display = 'block';
                noPlayerSelected.style.display = 'none';
            } else {
                // 没有选中的玩家
                selectedPlayerInfo.style.display = 'none';
                noPlayerSelected.style.display = 'block';
            }
        }
        
        // 从选中列表中移除玩家
        function removePlayerFromSelection(playerId) {
            // 移除玩家
            selectedPlayers = selectedPlayers.filter(p => p.id !== playerId);
            
            // 取消对应复选框的选中状态
            const checkbox = document.querySelector(`.player-checkbox[value="${playerId}"]`);
            if (checkbox) {
                checkbox.checked = false;
                const row = checkbox.closest('tr');
                if (row) {
                    row.classList.remove('selected');
                }
            }
            
            // 更新显示
            updateSelectedPlayersDisplay();
            updateSendButtonState();
        }
        
        // 加载物品分类
        async function loadItemCategories() {
            try {
                const token = sessionStorage.getItem('gmToken');
                if (!token) {
                    showMessage('未找到认证令牌，请重新登录', 'error');
                    return;
                }
                
                // 发送请求获取物品分类
                const response = await fetch('/gm/itemsCategory', {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                        'token': token
                    }
                });
                
                const result = await response.json();
                
                if (result.code === 200 && result.data) {
                    itemCategories = result.data;
                    populateItemCategories(result.data);
                } else {
                    showMessage(result.message || '获取物品分类失败', 'error');
                }
            } catch (error) {
                console.error('加载物品分类出错:', error);
                showMessage('加载物品分类时发生错误', 'error');
            }
        }
        
        // 填充物品分类下拉框
        function populateItemCategories(categories) {
            const selectElement = document.getElementById('itemCategory');
            selectElement.innerHTML = '<option value="">请选择物品分类</option>';
            
            // 将分类按值排序
            const sortedCategories = Object.entries(categories).sort((a, b) => a[1] - b[1]);
            
            sortedCategories.forEach(([categoryName, categoryValue]) => {
                const option = document.createElement('option');
                option.value = categoryValue;
                option.textContent = categoryName;
                selectElement.appendChild(option);
            });
        }
        
        // 添加物品到列表
        function addItemToList() {
            // 获取输入的物品信息
            const categoryId = document.getElementById('itemCategory').value;
            const itemId = document.getElementById('itemId').value.trim();
            const itemCount = document.getElementById('itemCount').value.trim() || '1'; // 设置默认值为'1'

            // 验证输入
            if (!categoryId) {
                showMessage('请选择物品分类', 'warning');
                return;
            }

            if (!itemId) {
                showMessage('请输入物品ID', 'warning');
                return;
            }

            // 改进验证逻辑，处理空值和无效值
            if (!itemCount || isNaN(itemCount) || parseInt(itemCount) <= 0) {
                showMessage('请输入有效的物品数量', 'warning');
                return;
            }

            // 将物品添加到待发送列表 - 存储物品类型和数量
            const count = parseInt(itemCount);
            const typeId = parseInt(categoryId);

            // 使用复合键存储物品信息（类型+ID）
            const key = `${typeId}-${itemId}`;
            itemsToSend[key] = {
                itemType: typeId,
                itemId: parseInt(itemId),
                itemCount: count
            };

            // 更新物品列表显示
            updateItemsList();

            // 显示成功消息
            showMessage('物品已添加到列表', 'success');

            // 清空输入框
            document.getElementById('itemId').value = '';
            document.getElementById('itemCount').value = '1'; // 重置为默认值
        }
        
        // 从列表中移除物品
        function removeItemFromList(itemId) {
            delete itemsToSend[itemId];
            updateItemsList();
            showMessage('物品已从列表中移除', 'info');
        }
        
        // 更新物品列表显示
        function updateItemsList() {
            const itemsList = document.getElementById('itemsList');
            const sendButton = document.getElementById('sendItemsBtn');
            
            // 检查是否有物品
            const hasItems = Object.keys(itemsToSend).length > 0;
            
            // 清空列表
            itemsList.innerHTML = '';
            
            if (hasItems) {
                // 启用发送按钮
                sendButton.disabled = selectedPlayers.length === 0;
                
                // 添加物品到列表
                Object.entries(itemsToSend).forEach(([key, item]) => {
                    const itemElement = document.createElement('div');
                    itemElement.className = 'item-list-item';
                    itemElement.innerHTML = `
                        <span class="item-info">类型: ${item.itemType}, 物品ID: ${item.itemId}, 数量: ${item.itemCount}</span>
                        <button class="btn-remove" onclick="removeItemFromList('${key}')">移除</button>
                    `;
                    itemsList.appendChild(itemElement);
                });
            } else {
                // 创建并添加空列表提示元素
                const emptyList = document.createElement('div');
                emptyList.id = 'emptyItemsList';
                emptyList.className = 'empty-list';
                emptyList.textContent = '物品列表为空，请先添加物品';
                itemsList.appendChild(emptyList);
                // 禁用发送按钮
                sendButton.disabled = true;
            }
        }
        
        // 从列表发送物品
        async function sendItemsFromList() {
            if (selectedPlayers.length === 0) {
                showMessage('请先选择一个玩家', 'warning');
                return;
            }
            
            if (Object.keys(itemsToSend).length === 0) {
                showMessage('物品列表为空，请先添加物品', 'warning');
                return;
            }
            
            try {
                const token = sessionStorage.getItem('gmToken');
                if (!token) {
                    showMessage('未找到认证令牌，请重新登录', 'error');
                    return;
                }
                
                // 构造请求数据 - 按照新的接口文档格式
                const requestData = {
                    userIds: selectedPlayers.map(p => p.id),
                    obtainItemList: Object.values(itemsToSend)
                };
                
                // 发送请求到 /gm/sendItem 接口
                const response = await fetch('/gm/sendItem', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'token': token
                    },
                    body: JSON.stringify(requestData)
                });
                
                const result = await response.json();
                
                if (result.code === 200) {
                    showMessage(`成功向 ${selectedPlayers.length} 位玩家发放道具`, 'success');
                    // 清空物品列表
                    itemsToSend = {};
                    updateItemsList();
                } else {
                    showMessage(result.message || '发送物品失败', 'error');
                }
            } catch (error) {
                console.error('发送物品出错:', error);
                showMessage('发送物品时发生错误', 'error');
            }
        }
        
        // 更新玩家选择状态时同时更新发送按钮状态
        function updateSendButtonState() {
            const sendButton = document.getElementById('sendItemsBtn');
            sendButton.disabled = selectedPlayers.length === 0 || Object.keys(itemsToSend).length === 0;
        }
        

        

        
        // 直播间管理相关功能已删除
        

    </script>
</body>
</html>